import dayjs from "dayjs";
import isToday from "dayjs/plugin/isToday";
import { PxButton } from "px-ui";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";

dayjs.extend(isToday);

export const formatSpanFn = (data: Array<any>): Array<any> => {
  if (!data?.length) return [];
  let currentGasNameNum = 0;
  let currentStationNum = 0;
  let currentDeviceCode = "";
  let currentDeviceCodeIndex = 0;
  data?.forEach((item, index, arr) => {
    const { deviceCode, station } = item;
    if (index === 0) {
      currentDeviceCode = deviceCode;
      currentDeviceCodeIndex = 0;
    } else if (deviceCode !== currentDeviceCode) {
      currentDeviceCode = deviceCode;
      currentDeviceCodeIndex++;
    }
    item["index"] = currentDeviceCodeIndex;
    currentGasNameNum++;
    currentStationNum++;
    if (deviceCode !== arr[index + 1]?.deviceCode) {
      data[index - currentGasNameNum + 1]["rowspan"] = currentGasNameNum;
      currentGasNameNum = 0;
      data[index - currentStationNum + 1]["rowspan2"] = currentStationNum;
      currentStationNum = 0;
    } else {
      if (station !== arr[index + 1]?.station) {
        data[index - currentStationNum + 1]["rowspan2"] = currentStationNum;
        currentStationNum = 0;
      }
    }
  });
  return data;
};

export const formatBottomTableDataFn = (formatSpanData: Array<any>, gasCheckInfoResDTOList: Array<any>, scheduleEmployeeInfoDTOList: Array<any>) => {
  const inspectionPerson = {
    deviceCode: "点检人",
    isInspectionPerson: true,
    isFixed: true,
    scheduleEmployeeInfoDTOList
  };
  const systemEngineer = {
    deviceCode: "系统工程师",
    isSystemEngineer: true,
    isFixed: true,
    scheduleEmployeeInfoDTOList
  };
  formatSpanData[0]?.dayValues?.forEach((item, index) => {
    const { planTimeDayStr = "" } = item;
    const t = gasCheckInfoResDTOList?.find(item => item?.itemDate === planTimeDayStr);
    if (t) {
      const { checkerInfo = null, engineerInfo = null, itemDate = "" } = t;
      const checkerInfoArr = [checkerInfo?.operator, checkerInfo?.operatorName]?.filter(item => !!item);
      const engineerInfoArr = [engineerInfo?.operator, engineerInfo?.operatorName]?.filter(item => !!item);
      inspectionPerson[`readValue_f_${index}`] =
        checkerInfoArr.length === 2 ? checkerInfoArr.join(" / ") : checkerInfoArr.length === 1 ? checkerInfoArr[0] : "";
      // if (dayjs(itemDate).isToday()) {
      // 特气 点检放在当天的前一天 bugid 28341
      if (dayjs(itemDate).isSame(dayjs().subtract(1, "day"), "day")) {
        inspectionPerson["inspectionPersonKey"] = `readValue_f_${index}`;
        inspectionPerson["itemDate"] = itemDate;
        systemEngineer["inspectionPersonName"] =
          checkerInfoArr.length === 2 ? checkerInfoArr.join(" / ") : checkerInfoArr.length === 1 ? checkerInfoArr[0] : "";
      }
      systemEngineer[`readValue_f_${index}`] =
        engineerInfoArr.length === 2 ? engineerInfoArr.join(" / ") : engineerInfoArr.length === 1 ? engineerInfoArr[0] : "";
      // if (dayjs(itemDate).isToday()) {
      // 特气 确认放在当天的前一天 bugid 28341
      if (dayjs(itemDate).isSame(dayjs().subtract(1, "day"), "day")) {
        systemEngineer["systemEngineerKey"] = `readValue_f_${index}`;
        systemEngineer["itemDate"] = itemDate;
      }
    }
  });
  return [inspectionPerson, systemEngineer];
};

export const formatTableDataFn = (res: Record<string, any>): Array<any> => {
  const { recordItemResDTOList, gasCheckInfoResDTOList, scheduleEmployeeInfoDTOList } = res;
  if (!recordItemResDTOList?.length) return [];
  const formatData = recordItemResDTOList?.map(item => {
    const { dayValues = [], station = "" } = item;
    const ext = dayValues?.reduce((pre, cur, index, arr) => {
      if (index === arr.length - 1) {
        return pre;
      } else {
        const { planTimeDayStr = "", supplyStatusL = "", supplyStatusR = "", valueDayHourList = [] } = cur;
        const {
          supplyStatusL: supplyStatusL_2 = "",
          supplyStatusR: supplyStatusR_2 = "",
          valueDayHourList: valueDayHourList_2 = []
        } = arr[index + 1];
        const fd = valueDayHourList?.filter(item => item.groupCode === "GAS_SPECIALTY_CHECK_THIRTEEN"); // 过滤当天 13：00
        const sd = valueDayHourList_2?.filter(item => item.groupCode === "GAS_SPECIALTY_CHECK_ONE"); // 过滤第二天 01：00
        pre[`readValue_f_${index}`] = fd[0]?.readValue;
        pre[`readValue_s_${index}`] = sd[0]?.readValue;
        // if (dayjs(planTimeDayStr).isToday()) {
        //   pre[`supplyStatus_${index}`] = station === "L" ? supplyStatusL : station === "R" ? supplyStatusR : "";
        // } else {
        //   pre[`supplyStatus_${index}`] = station === "L" ? supplyStatusL_2 : station === "R" ? supplyStatusR_2 : "";
        // }
        pre[`supplyStatus_${index}`] = station === "L" ? supplyStatusL_2 : station === "R" ? supplyStatusR_2 : "";
        return pre;
      }
    }, {});
    return { ...item, ...ext };
  });
  const formatSpanData = formatSpanFn(formatData);
  const formatBottomTableData = formatBottomTableDataFn(formatSpanData, gasCheckInfoResDTOList, scheduleEmployeeInfoDTOList);
  return [...formatSpanData, ...formatBottomTableData];
};

export const formatDateTableCloumnsFn = (data: Array<any>, cb: (scope: any) => void, cb2: (scope: any) => void): Array<any> => {
  if (!data?.length) return [];
  return data[0]?.dayValues?.reduce((pre, cur, index, arr) => {
    if (index === arr.length - 1) {
      return pre;
    } else {
      const { planTimeDayStr: label = "", valueDayHourList = [] } = cur;
      const fd = valueDayHourList?.filter(item => item.groupCode === "GAS_SPECIALTY_CHECK_THIRTEEN"); // 过滤当天 13：00
      const sd = arr[index + 1]?.valueDayHourList?.filter(item => item.groupCode === "GAS_SPECIALTY_CHECK_ONE"); // 过滤第二天 01：00
      const render = scope => {
        const {
          row: {
            isInspectionPerson = false,
            isSystemEngineer = false,
            inspectionPersonKey = "",
            systemEngineerKey = "",
            scheduleEmployeeInfoDTOList = [],
            inspectionPersonName = ""
          },
          column: { property = "" }
        } = scope;

        const styleFn = () => {
          const textAlign = isInspectionPerson || isSystemEngineer ? "center" : "left";
          const fontWeight = isInspectionPerson || isSystemEngineer ? 600 : undefined;
          return { textAlign, fontWeight };
        };

        const styleFn2 = () => {
          const textAlign = isInspectionPerson || isSystemEngineer ? "center" : "left";
          const fontWeight = isInspectionPerson || isSystemEngineer ? 600 : undefined;
          return { textAlign, fontWeight };
        };

        if (isInspectionPerson || isSystemEngineer) {
          const userInfo = localStorage.getItem("userInfo");
          const { userId = null } = JSON.parse(userInfo);
          if (inspectionPersonKey === property) {
            return () =>
              scope.row[property] ? (
                <div style={styleFn()}>{scope.row[property] || "--"}</div>
              ) : (
                <div style={styleFn2()}>
                  <PxButton
                    type="primary"
                    size="small"
                    disabled={!scheduleEmployeeInfoDTOList?.some(item => item.userId === Number(userId))}
                    vHas={"GAS_CONSUMPTION_SPECIALGAS_INSPECTION_BTN"}
                    onClick={useThrottleFn(() => cb && cb(scope), delay)}
                  >
                    {"点检"}
                  </PxButton>
                </div>
              );
          } else if (systemEngineerKey === property) {
            return () =>
              scope.row[property] ? (
                <div style={styleFn()}>{scope.row[property] || "--"}</div>
              ) : (
                <div style={styleFn2()}>
                  <PxButton
                    type="primary"
                    size="small"
                    disabled={!inspectionPersonName}
                    vHas={"GAS_CONSUMPTION_SPECIALGAS_INSPECTION_CONFIRM_BTN"}
                    onClick={useThrottleFn(() => cb2 && cb2(scope), delay)}
                  >
                    {"确认"}
                  </PxButton>
                </div>
              );
          } else {
            return () => <div style={styleFn()}>{scope.row[property] || "--"}</div>;
          }
        } else {
          return () => <div style={styleFn()}>{scope.row[property] ?? "--"}</div>;
        }
      };
      const f = {
        label: fd[0]?.planTimeHourStr,
        prop: `readValue_f_${index}`,
        render
      };
      const s = {
        label: sd[0]?.planTimeHourStr,
        prop: `readValue_s_${index}`
      };
      const children = [f, s];
      const prop = "planTimeDayStr";
      const renderHeader = () => {
        return () => <div style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>{label}</div>;
      };
      const d = { label, prop, renderHeader };
      d["children"] = children;
      pre.push(d);
      const status = {
        label: "供应状态",
        prop: `supplyStatus_${index}`
      };
      pre.push(status);
      return pre;
    }
  }, []);
};
